<?php

/**
 * This program is send WECHAT message temporary due to the courier is not yet ready.
 */


function sendWeChatMessage($inputMessage, $inputSubject = "", $inputReceiver = __WECHAT_RECIVER__)
{

    Yii::info("WeChat Message Sending, subject is {$inputSubject}");
    messageSend($inputMessage, $inputSubject, $inputReceiver);

}

function messageSend(string $storedMessages, $inputSubject, $inputReceiver)
{
    if (!wechatCorpSend($storedMessages, $inputSubject, $inputReceiver)) {
        Yii::warning("Corp WeChat send failed, turned to use sc_send.");
        sc_send($storedMessages);
    }
}

function sc_send( $desp,  $text = '大事不妙' ,  $key = __MESSENGER_WECHAT_FCQQ_TOKEN__  )
{
    $postdata = http_build_query(
        array(
            'text' => $text,
            'desp' => $desp
        )
    );

    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );
    $context  = stream_context_create($opts);
    return $result = file_get_contents('https://sc.ftqq.com/'.$key.'.send', false, $context);

}


function wechatCorpRegetToken($inputCorpId, $inputCorpSecret):string
{
    $redis  =   Yii::$app->redis;
    $redis  ->  del("WeChatCorp_Token");
    return wechatCorpGetToken($inputCorpId, $inputCorpSecret);
}

function wechatCorpGetToken($inputCorpId, $inputCorpSecret):string
{

//	return "-NS3m3loS7XpC9J5KewAUfrgbuEZJL6y5Pb7suNY-HXmcWSj46hO74CJyATICRYebieureG1yf4KkRp-a2g-hP_GgoH3LPhkjUzQqs9QVCy5TKp_WkiE8AU4cxjTQZcXXXt0snvTrb0-K7kuiPhWsWpqn3vi8YI0RlAp9exbC9yzmXTZyD4Swu8WKfQVyvEh7XOdWKZITBNFsYHwimlHRwkqHDjrKC6hRz-u54vkbL8dBxsuJAvgojcp8FdHT0NGTJC5VnEesNK_j53thMeTOM6M7YGCzJHlLmQn53lV6l8";
    $redis  =   Yii::$app->redis;
    if(is_null($accessToken = $redis->get("WeChatCorp_Token")))
    {
        $curlHandler = curl_init();

        $requireURL	=	"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$inputCorpId}&corpsecret={$inputCorpSecret}";
        curl_setopt($curlHandler, CURLOPT_URL,            $requireURL);
        curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlHandler, CURLOPT_HEADER,         false);
        curl_setopt($curlHandler, CURLOPT_TIMEOUT, 	       30);
        curl_setopt($curlHandler,CURLOPT_SSL_VERIFYPEER,false); ;
        curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, true);

        $output = curl_exec($curlHandler);
//	$curlInfo = curl_getinfo($curlHandler);
        curl_close($curlHandler);


        //todo: 错误码判断
        if("" != $output)
        {
            $accessToken    =   json_decode($output) ->access_token;
            Yii::info("Get Corp WeChat ACCESS_TOKEN is: {$accessToken}");
            $redis->setex("WeChatCorp_Token", __WECHAT_ONE_HOUR_SECONDS__, $accessToken);
        }
        else {
            Yii::error("Get Corp WeChat ACCESS_TOKEN Failed!");
            return false;
        }
    }
	return $accessToken;
}

function wechatCorpSend($inMessage, $inputSubject, $inputReceiver)
{
	static $accessToken	=	null;
	$processStatus		=	false;
	if (null == $accessToken) {
		if (!$accessToken = wechatCorpGetToken(__WECHAT_TOKEN_CORPID__, __WECHAT_TOKEN_SERECT__)) {
			return false;
		}
	}

	$sendInfo	=	array(	'touser' 		=> $inputReceiver,
							'toparty'		=> "",
							'totag'			=> "",
							'msgtype'		=> "text",
							'agentid'		=> __WECHAT_AGENT_ID__,
							'text'			=> array('content' => $inputSubject."\n".$inMessage),
							'safe'			=> 0);
	$sendMessage = json_encode($sendInfo);

	$curlHandler = curl_init();
	do {
		$repeatSend	=	false;
		curl_setopt($curlHandler, CURLOPT_URL, "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$accessToken}");
		curl_setopt($curlHandler, CURLOPT_TIMEOUT, 30);
		curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书

		curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curlHandler, CURLOPT_POST, true);
		curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $sendMessage);
		$ret = curl_exec($curlHandler);
		$ret_decode = json_decode($ret, true);

		if(!isset($ret_decode['errcode']))
		{
			$ret_decode['errcode']	=	__WECHAT_TOKEN_ERROR_INVALID__;
		}

		switch ($ret_decode['errcode']) {
			case __WECHAT_RETURN_SUCCESS__:
                Yii::info("Send successfully.");
				$processStatus	=	true;
				break;
			case __WECHAT_TOKEN_ERROR_EXPIRED__:
			case __WECHAT_TOKEN_ERROR_INVALID__:
			    Yii::warning("Corp WeChat Send temporary failed, return code = {$ret_decode['errcode']}, try to REGet ACCESS_TOKEN.");
				$accessToken =  wechatCorpRegetToken(__WECHAT_TOKEN_CORPID__, __WECHAT_TOKEN_SERECT__);
				$repeatSend = true;
//				Logger::getLogger('wechat')->info("TOKEN EXPIRED, REFETCH TOKEN.");
				break;
			default:
                Yii::error("Corp WeChat Send failed, return code = {$ret_decode['errcode']}.");
				$processStatus =	false;
//				Logger::getLogger('wechat')->warn("CORP WECHAT SEND FAILED, RC = ".json_decode($ret)->errcode);
				break;
		}

	} while ($repeatSend);
	curl_close($curlHandler);

	return $processStatus;
}


?>